<template>
  <div>
    <AdTable @register="registerTable">
      <template #toolbar>
        <Authority :value="'Root.Admin.Auth.UserEntity.Create'">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />
            {{ t('routes.system.authorization.userEntity.addUserEntity') }}
          </a-button>
        </Authority>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column?.key === 'action'">
          <TableAction
            stopButtonPropagation
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: t('common.delText'),
                auth: 'Root.Admin.Auth.UserEntity.Delete', // 权限控制
                ifShow: (_action) => {
                  return record?.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
                },
                popConfirm: {
                  title: t('common.delConfirmText'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
              {
                icon: 'clarity:note-edit-line',
                tooltip: t('common.editText'),
                auth: 'Root.Admin.Auth.UserEntity.Update', // 权限控制
                ifShow: (_action) => {
                  return record?.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
                },
                onClick: handleEdit.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
      <template #expandedRowRender="{ record }">
        <FilterContainer
          :filterGroup="record.FilterGroup"
          :parentGroup="undefined"
          :entityType="record.EntityType"
          :getPropertiesApi="getEntityProperties"
        />
        <a-button
          v-if="record.FilterGroup"
          type="default"
          style="margin: 5px"
          @click="showGroupJson(record)"
        >
          {{ t('routes.system.authorization.userEntity.showGroupJson') }}
        </a-button>
        <a-button
          v-if="record.FilterGroup"
          type="primary"
          style="margin: 5px"
          @click="saveFilterGroup(record)"
        >
          {{ t('common.saveText') }}
        </a-button>
        <Alert
          v-if="record.groupJson"
          :message="t('routes.system.authorization.userEntity.filterGroupJson')"
          :description="record.groupJson"
          type="info"
          show-icon
        >
          <template #icon><Icon icon="mdi:code-json" size="26" /></template>
        </Alert>
      </template>
    </AdTable>
  </div>
</template>

<script lang="ts" setup>
  import { Alert } from 'ant-design-vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import Icon from '@/components/Icon/Icon.vue';
  import { Authority } from '@/components/Authority';
  import { FilterContainer } from '@/components/FilterContainer';
  import { FilterGroup } from '#/request';

  import { AdTable, useAdTable, TableAction } from '@/components/AdTable';
  import {
    readUserEntities,
    createUserEntities,
    updateUserEntities,
    deleteUserEntities,
  } from '@/api/authorization/admin/userentity';
  import { readEntityInfoProperties } from '@/api/authorization/admin/entityinfo';
  import { FormModeEnum } from '@/enums/formEnum';

  import { columns } from './userentity.data';

  defineOptions({ name: 'UserEntityPage' });

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const [registerTable, { openDetailForm, reload }] = useAdTable({
    // 表标题呈现器
    title: t('routes.system.authorization.userEntity.userEntityList'),
    // 表格数据接口请求对象
    api: readUserEntities,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'auth_userentity_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('routes.system.authorization.userEntity.title'),
      // 实体新增接口请求对象
      createApi: createUserEntities,
      // 实体更新接口请求对象
      updateApi: updateUserEntities,
    },
    // 表单列信息 BasicColumn[]
    columns: columns,
    rowKey: 'Id',
    expandRowByClick: true,
    // 是否可拖拽列
    canColDrag: true,
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    //表格设置项
    tableSetting: { redo: true, size: true, setting: true, fullScreen: true },
    // 是否显示表格边框
    bordered: false,
    // 是否显示序号列
    showIndexColumn: true,
    // 表格右侧操作列配置 BasicColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  /** 处理创建 */
  async function handleCreate() {
    openDetailForm(FormModeEnum.Add);
  }

  /** 处理编辑 */
  async function handleEdit(record: any) {
    openDetailForm(FormModeEnum.Edit, record);
  }

  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log(record);
    const result = await deleteUserEntities([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      reload();
    }
  }

  /** 获取实体信息属性集合 */
  async function getEntityProperties(typeName: string) {
    // console.log(typeName);
    const result = await readEntityInfoProperties(typeName);
    if (result.Succeeded) {
      return result.Data;
    }
    return [];
  }

  /** 显示JSON */
  function showGroupJson(item: any) {
    const filterGroup = item.FilterGroup as FilterGroup;
    item.groupJson = JSON.stringify(filterGroup, null, 2);
  }
  /** 保存筛选规则JSON */
  async function saveFilterGroup(item: any) {
    const dto = {
      Id: item.Id,
      UserId: item.UserId,
      EntityId: item.EntityId,
      Operation: item.Operation,
      FilterGroup: item.FilterGroup,
      IsLocked: item.IsLocked,
      DataVersion: item.DataVersion,
    };
    const result = await updateUserEntities([dto]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      reload();
    }
  }
</script>
